-- FUNCTION: public.udf_FetchPatients_For_AppointmentScheduleFollowUp(character varying, character varying, character varying, character varying, integer)

-- DROP FUNCTION IF EXISTS public."udf_FetchPatients_For_AppointmentScheduleFollowUp"(character varying, character varying, character varying, character varying, integer);

CREATE OR REPLACE FUNCTION public."udf_FetchPatients_For_AppointmentScheduleFollowUp"(
	filter character varying DEFAULT NULL::text,
	"patientMobile" character varying DEFAULT NULL::text,
	"patientName" character varying DEFAULT NULL::text,
	"urlLink" character varying DEFAULT NULL::text,
	"appointmentId" integer DEFAULT NULL::integer)
    RETURNS TABLE("IdProofName" character varying, "RelativeName" character varying, "Relation" character varying, "EducationName" text, "HowDidYouKnow" text, "OccupationName" text, "PatientId" integer, "Salutation" character varying, "FirstName" text, "MiddleName" text, "LastName" text, "FullName" text, "DateOfBirth" date, "Age" smallint, "Gender" character, "MaritalStatus" character, "UMRNo" character varying, "Email" character varying, "Mobile" character varying, "StreetAddress" character varying, "Area" character varying, "City" character varying, "State" character varying, "Zipcode" character varying, "CountryId" integer, "ProfileImageUrl" text, "ThumbnailUrl" text, "Active" boolean, "CreatedBy" integer, "CreatedDate" timestamp without time zone, "ModifiedBy" integer, "ModifiedDate" timestamp without time zone, "Guid" uuid, "ReferralBy" integer, "ReferralCode" character varying, "AadharNo" character varying, "ReferredBy" character varying, "ReferredByName" character varying, "FatherOrHusband" text, "HWCPatientId" integer, "Education" character varying, "Occupation" character varying, "Religion" character varying, "Nationality" character varying, "PatientReferredById" integer, "IdProofValue" character varying, "IdProofId" integer, "BloodGroup" character varying, "Amount" numeric, "PaymentStatus" boolean, "TempPatient" boolean, "HowDidYouKnowId" integer, "EducationId" integer, "OccupationId" integer, "BirthMark1" text, "BirthMark2" text, "RelationType" text, "OccupationDetail" text, "IsNewPatient" boolean, "REGID" character varying, "REGNO" integer, "InsuranceCompanyId" integer, "ProviderId" integer, "AppointmentId" integer, "PatientType" character, "AppointmentNo" character varying, "AppointmentTime" time without time zone, "AppointmentEndTime" time without time zone, "AppointmentNotes" character varying, "CouponId" integer, "AppointmentAmount" numeric, "Discount" numeric, "Total" numeric, "Status" character, "PatientFamilyId" integer, "DepartmentId" integer, "PaymentType" character varying, "PaymentNumber" character varying, "AppointmentPaymentStatus" boolean, "VisitTypeId" integer, "ChargeTypesId" integer, "LocationId" integer, "AppointmentTypeId" integer, "PayTypeId" integer, "TokenNumber" integer, "SpecializationId" integer, "ProviderAvailabilityId" integer, "ConsultationTypeId" integer, "DoctorSpecializationChargeModuleDetailsId" integer, "OtherRemarks" character varying, "AuthorityMasterId" integer, "ReasonsId" integer, "Remarks" character varying, "ProviderName" character varying , "ModuleName" character varying, "AppointmentDate" timestamp without time zone, "isActiveAppointmentExists" boolean, "HWCName" character varying, "Description" text, "RowColor" text) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN

return query

with cts as (
select row_number() over(partition by a."PatientId" order by  a."AppointmentId" desc,
						 a."AppointmentDate" desc )"Max" ,a."PatientId",a."AppointmentId" 
	from "Appointment" a
join  "Patient" pat  on  a."PatientId"	=pat."PatientId"
	join "Provider" pr on a."ProviderId" = pr."ProviderId"
where a."Active"=true 	 
	--and	case when "filter" is null then 1=1 else (TRIM(UPPER(pat."FullName")) ILIKE '%' OR pat."UMRNo"  ilike'%'  OR pat."Mobile" ILIKE '%')|| "filter"||'%' end
	and case when "filter" is null then 1=1 else  TRIM(UPPER(pat."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."UMRNo")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."Mobile")) ilike'%'|| "filter"||'%'  end
	and	case when "patientMobile" is null then 1=1 else  pat."Mobile"  ilike'%'|| "patientMobile"||'%' end
	and	case when "patientName" is null then 1=1 else  pat."FullName"  ilike'%'|| "patientName"||'%' end
	and case when "appointmentId" is null then 1=1 else a."AppointmentId" = "appointmentId" end
)
, maxapt as (
select a.* from "Appointment" a
join cts on a."AppointmentId"=cts."AppointmentId"
where "Max"=1)

SELECT DISTINCT

id."IdProofName",pf."FullName" as "RelativeName",pf."Relation",
eid."Name" as "EducationName",hid."Name" as "HowDidYouKnow",oid."Name" as "OccupationName",

   pat."PatientId",pat. "Salutation",pat. "FirstName",pat. "MiddleName",pat. "LastName",pat. "FullName",pat. "DateOfBirth",pat. "Age",pat. "Gender",pat. "MaritalStatus",pat. "UMRNo",pat. "Email",pat. "Mobile",pat. "StreetAddress",pat. "AddressLine2" as "Area",pat. "City",pat. "State",pat. "Zipcode",pat. "CountryId"
,(CASE WHEN pat."ProfileImageUrl" IS NOT NULL THEN CONCAT("urlLink",'/', pat."Guid", '/', pat."ProfileImageUrl") ELSE '' END) AS "ProfileImageUrl"
,(CASE WHEN pat."ThumbnailUrl" IS NOT NULL THEN CONCAT("urlLink", '/', pat."Guid", '/', pat."ThumbnailUrl") ELSE '' END) AS "ThumbnailUrl"
,pat. "Active",pat. "CreatedBy",pat. "CreatedDate",pat. "ModifiedBy",pat. "ModifiedDate",pat. "Guid",pat. "ReferralBy",pat. "ReferralCode",pat. "AadharNo",referred."Name" as "ReferredBy",pat. "ReferredByName",pat. "FatherOrHusband",pat. "HWCPatientId",pat. "Education",pat. "Occupation",pat. "Religion",pat. "Nationality",pat. "PatientReferredById",pat. "IdProofValue",pat. "IdProofId",pat. "BloodGroup",pat. "Amount",pat. "PaymentStatus",pat. "TempPatient",pat. "HowDidYouKnowId",pat. "EducationId",pat. "OccupationId",pat. "BirthMark1",pat. "BirthMark2",pat. "RelationType",pat. "OccupationDetail",pat. "IsNewPatient",pat. "REGID",pat. "REGNO",pat. "InsuranceCompanyId",
	
	
	apt."ProviderId",	
	 apt."AppointmentId", 
	 apt."PatientType", 
	 apt."AppointmentNo"
	 ,apt."AppointmentTime"
	 ,apt. "AppointmentEndTime"
	 ,apt. "AppointmentNotes",
	 apt."CouponId",
	 apt. "Amount" as "AppointmentAmount",
	 apt."Discount"
	 ,apt. "Total"
	 ,apt. "Status"
	 ,apt. "PatientFamilyId"
	 ,apt. "DepartmentId"
	 ,apt. "PaymentType"
	 ,apt. "PaymentNumber"
	 ,apt. "PaymentStatus"
	 , apt."VisitTypeId"
	 , apt."ChargeTypesId"
	 , apt."LocationId"
	 , apt."AppointmentTypeId"
	 , apt."PayTypeId"
	 , apt."TokenNumber"
	 , apt."SpecializationId"
	 , apt."ProviderAvailabilityId"
	 , apt."ConsultationTypeId"
	 , apt."DoctorSpecializationChargeModuleDetailsId"
	 , apt."OtherRemarks"
	 , apt."AuthorityMasterId"
	 , apt."ReasonsId"
	 , apt."Remarks"	 
	 
	,pr."FullName" as "ProviderName",MM."ModuleName"
,(max(apt."AppointmentDate")over(partition by apt."PatientId")::text ||' ' || max(apt."AppointmentTime")over(partition by apt."PatientId",apt."AppointmentDate")::text)::timestamp as "AppointmentDate",
(case when (max(apt."AppointmentDate")over(partition by apt."PatientId")::text ||' ' || max(apt."AppointmentTime")over(partition by apt."PatientId")::text)::timestamp > now() at time zone 'UTC-5:30' then true else false end)"isActiveAppointmentExists"
, HWC."HWCName", HWC."Description", HWC."RowColor"
FROM "Patient" pat  
left join maxapt apt on apt."PatientId" = pat."PatientId" and apt."Status" <> 'C' and apt."Active"=true
left join "Provider" pr on pr."ProviderId" = apt."ProviderId"
left join "HWCPatient"  HWC on HWC."HWCPatientId" = pat."HWCPatientId"
LEFT JOIN "PatientReferredBy" referred ON referred."PatientReferredById" = pat."PatientReferredById"
left join "IdProof" id on id."IdProofId" = pat."IdProofId"
left join "HowDidYouKnow" hid on hid."HowDidYouKnowId" = pat."HowDidYouKnowId"
left join "Education" eid on eid."EducationId" = pat."EducationId"
left join "Occupation" oid on oid."OccupationId" = pat."OccupationId"
left join "PatientFamily" pf on pf."PatientId" = pat."PatientId"
left join "WebNotification" wn on wn."PatientId" = pat."PatientId"
left join "ModulesMaster" MM on MM."ModulesMasterId" = wn."ModulesMasterId"
 WHERE  pat."Active" IS TRUE 
--and	case when "filter" is null then 1=1 else (TRIM(UPPER(pat."FullName")) ILIKE '%' OR pat."UMRNo"  ilike'%'  OR pat."Mobile" ILIKE '%')|| "filter"||'%' end
and case when "filter" is null then 1=1 else  TRIM(UPPER(pat."FullName")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."UMRNo")) ilike'%'|| "filter"||'%' OR  TRIM(UPPER(pat."Mobile")) ilike'%'|| "filter"||'%'  end
and	case when "patientMobile" is null then 1=1 else  pat."Mobile"  ilike'%'|| "patientMobile"||'%' end
and	case when "patientName" is null then 1=1 else  pat."FullName"  ilike'%'|| "patientName"||'%' end
and case when "appointmentId" is null then 1=1 else apt."AppointmentId" = "appointmentId" end
;

END
$BODY$;

ALTER FUNCTION public."udf_FetchPatients_For_AppointmentScheduleFollowUp"(character varying, character varying, character varying, character varying, integer)
    OWNER TO postgres;



